package org.seckill.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashSet;
import java.util.Set;

/**
 * 使用两个线程测试符合场景
 *
 * 当执行某个操作有瞬间耗时（延时），如果请求过快那就会出现业务上的数据并发不一致性问题
 *
 *
 * @author chenhs
 * @date 2019/1/16
 */
@Controller
@RequestMapping("/hello")
public class HelloController {

    private static final Object lock = new Object();
    private static volatile Set<Long> payingIdSet = new HashSet<>();

    @RequestMapping(value = "/pinFa")
    @ResponseBody
    public String pinFa(Long id) {

        String x = "well done, man...!";

        synchronized (lock) {
            // 确保volatile对象的线程安全，复制操作
            Set<Long> copy = new HashSet<>(payingIdSet);
            if (copy.contains(id)) {
                System.out.println("【ReceiptWithdraw】提现ID为" + id + "的提现记录正在其他地方进行支付");
            } else {
                copy.add(id);
                System.out.println("【ReceiptWithdraw】正在支付提现ID为" + id + "的提现记录");
                payingIdSet = copy;
            }
        }
        try {

            //模拟订单支付耗时...
            Thread.sleep(800);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            synchronized (lock) {
                Set<Long> copy = new HashSet<>(payingIdSet);
                copy.remove(id);
                payingIdSet = copy;
            }
        }

        return x;
    }


}
